import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { StateCode } from '@/enums/apiResult'
import { useUserStore } from '@/store/modules/userStore'
import { router } from '@/router'
import { login } from './user'

const PathWhiteList = ['/api/user/login', '/api/user/register']

const api: AxiosInstance = axios.create({
    baseURL: 'http://localhost:8066/',
    timeout: 5000
})

//请求拦截器
api.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const store = useUserStore()
    const token = store.token
    if (token) {
        config.headers[store.tokenHeader] = `Bearer ${token}`
    }
    return config
}, (error: AxiosError) => {
    ElMessage({
        message: error.message,
        type: 'error'
    })
    return Promise.reject(error)
})


const showError = (msg:string,data:any) => {
    ElMessage({
        message: `${msg},${data}`,
        type: 'error'
    })
}

//响应拦截器
api.interceptors.response.use((res: AxiosResponse) => {
    const { code, msg, data } = res.data
    switch (code) {
        case StateCode.SUCCESS:
            return data;
        case StateCode.ERROR_AUTHENTICATION_VALID:
            //登录已过期跳转到登录页面
            showError(msg,data)
            router.replace('Login')
            break;
        default:
            showError(msg,data)
            return Promise.reject(code)
    }


}, ((error: AxiosError) => {
    ElMessage({
        message: error.message,
        type: 'error'
    })
    return Promise.reject(error)
}));


//手动设置返回类型，帮编译器正确识别类型
export const http = {
    get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return api.get(url, config)
    },
    post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
        return api.post(url, data, config)
    },
    put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
        return api.put(url, data, config)
    },
    delete<T = any>(url: string, config: AxiosRequestConfig): Promise<T> {
        return api.delete(url, config)
    }

}